<?
/*
* ===========================================*
* 函数说明:
* ===========================================*
*/
	class _stat
	{

		var $tmpDir = TMPDIR;
		var $userDataDir;
		var $userData;
		var $userTodayDir;
		var $time;
		var $year;
		var $month;
		var $day;
		var $week;
		var $hour;
		var $newDay = false;
		var $newViewer = true;
		var $viewerInfo = array();
		var $arrTypes = array(
										'keyword'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>false ),
										'referer'=>array( 'lastpage'=>true, 'allownull'=> true, 'newviewer'=>true ),
										'color'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'screen'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'language'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'browser'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'system'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'country'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'province'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'city'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true ),
										'timezone'=>array( 'lastpage'=>false, 'allownull'=> false, 'newviewer'=>true ),
										'page'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>false ),
										'return'=>array( 'lastpage'=>true, 'allownull'=> false, 'newviewer'=>true )
										);


		var $dayStartTime;

		function _stat( )
		{
			global $tableList;

			$this->tableList = $tableList;
			$this->time = time();
			$this->year = date( 'Y', $this->time );
			$this->month = date( 'm', $this->time );
			$this->day = date( 'j', $this->time );
			$this->week = date( 'w', $this->time );
			$this->hour = date('G', $this->time );
			$this->dayStartTime = mktime(0, 0, 0, $this->month, $this->day, $this->year);

			$this->getUserDir();
			$this->getUserData();
			$this->checkNewDay();
			$this->getViewerInfo();
			$this->checkNewViewer();

			//处理alexa数据
			$this->addAlexa();

			$this->saveArr();
			$this->saveViewerInfo();



			$this->showArr = Array ( 	'dayCount'=>array('day_count','今日访问'),
														'dayIpCount'=>array('day_count_ip','今日IP'),
														'hourCount'=>array('hour'.$this->hour,'本小时访问'),
														'hourIpCount'=>array('hourip'.$this->hour,'本小时IP')
													);


			$res = $this->_query( " select * from " . $this->tableList[day_data] . " where times = {$this->dayStartTime}" );
			$dayData = mysql_fetch_array( $res, MYSQL_ASSOC );
			if( count( $dayData ) < 1 || $dayData[datadayid] < 1 )
			{
				$this->iniToday();
			}

			$updateStr = "day_count = day_count + 1, hour{$this->hour} = hour{$this->hour} + 1";
			if( $this->newViewer )
			{
				 $updateStr .= ", hourip{$this->hour} = hourip{$this->hour} + 1, day_count_ip = day_count_ip + 1 " ;
			}
			$sql = " update " . $this->tableList[day_data] . " set $updateStr where times = {$this->dayStartTime}";
			$this->_query( $sql );
			$this->outLog( $dayData );
		}

		function outLog( $dayData )
		{
			$_GET[show] = @array_flip ( $_GET[show] );

			foreach( $this->showArr as $key=>$val )
			{
				if( isset( $_GET[show][$key] ) )
				{
					$showStr .= '[' . $this->charset( $val[1] ) . ':' . $dayData["$val[0]"] . ']';
				}

			}

			$title = $this->charset( '流量统计分析系统' );
			if( $this->viewerInfo[type] == 2 )
			{
				echo "document.getElementById(\"OurplusCount\").innerHTML='<a href=\"" . $this->viewerInfo['counturl'] . "\" target=\"_blank\" title=\"Ourplus " . $title . "\"><img src=\"" . $this->viewerInfo['counturl'] . "/countlogo.gif\" style=\"border:0px;\"  align=\"absmiddle\"></a>';";
			}
			else
			{
				echo "document.write('<a href=\"" . $this->viewerInfo['counturl'] . "\" target=\"_blank\" title=\"Ourplus " . $title . "\"><img src=\"" . $this->viewerInfo['counturl'] . "/countlogo.gif\" style=\"border:0px;\"  align=\"absmiddle\"></a>');";
				if( trim( $showStr ) != '' )
				{
					echo "document.write('$showStr')";
				}
			}
		}

		function charset( $str )
		{
			return $this->viewerInfo[charset] == 'utf-8' ? utf82gb2312( $str ) : $str;
		}

		function getUserDir()
		{
			$this->userDataDir = $this->tmpDir;
			if( ! is_dir( $this->userDataDir ) )
			{
				if( ! mkdir( $this->userDataDir ) )
				{
					$this->_Error( 'Error In GetUserDir At ' . __line__ );
				}
			}
		}

		function getUserData()
		{
			$sql = "SELECT  `id` , `manager` , `password` , `site` , `sitename` , `sitedes` , `sitetype` , `qq` , `email` , `msn` FROM " . $this->tableList[users] . " ";
			$res = $this->_query( $sql );
			$retRows = mysql_num_rows( $res );

			if( $retRows == 1 )
			{
				$this->userData = $userData[0];
			}
			elseif ( $retRows == 0 )
			{
				$this->_Error( 'Uninstall, Error At ' . __line__ );
			}
			elseif ( $retRows > 1 )
			{
				$this->_Error( 'Database User Data Error' );
			}

			$this->userData = mysql_fetch_array( $res, MYSQL_ASSOC );
		}


		function checkNewDay()
		{
			$this->userTodayDir = $this->userDataDir . '/' . $this->dayStartTime;
			if( ! is_dir( $this->userTodayDir ) )
			{
				$this->newDay = true;
				mkdir( $this->userTodayDir );
				$this->clearYesterday();
				$this->iniToday();
			}
		}

		function checkNewViewer()
		{
			$sql = "SELECT count(*) as count FROM " . $this->tableList[ip] . " where ip = '{$this->viewerInfo[REMOTE_ADDR]}' and time > $this->dayStartTime ";
			$res = $this->_query( $sql );
			$count = mysql_fetch_array( $res, MYSQL_ASSOC );
			$count = intval( $count[count] );
			if( $count > 0 )
			{
				$this->newViewer = false;
			}
		}

		function clearYesterday()
		{
			$yesterdayStartTime = mktime (0, 0, 0, $this->month, $this->day-1, $this->year);


			$yesterdayYear = date( 'Y', $yesterdayStartTime );
			$yesterdayMonth = date( 'm', $yesterdayStartTime );
			$yesterdayDay = date( 'j', $yesterdayStartTime );
			$yesterdayWeek = date( 'w', $yesterdayStartTime );
			$yesterdayHour = date('G', $yesterdayStartTime );

			$res = $this->_query( " select * from " . $this->tableList[day_data] . " where times = $yesterdayStartTime" );
			$yesterdayData = mysql_fetch_array( $res, MYSQL_ASSOC );

			$yesterdayData[day_count] = intval( $yesterdayData[day_count] );
			$yesterdayData[day_count_ip] = intval( $yesterdayData[day_count_ip] );

			//Update Count Table
			$sql = "update " . $this->tableList[users] . " set week{$yesterdayWeek} = week{$yesterdayWeek} + $yesterdayData[day_count], weekip{$yesterdayWeek} = weekip{$yesterdayWeek} + $yesterdayData[day_count_ip],
			day{$yesterdayDay} = day{$yesterdayDay} + $yesterdayData[day_count], dayip{$yesterdayDay} = dayip{$yesterdayDay} + $yesterdayData[day_count_ip],
			all_count = all_count  + $yesterdayData[day_count], all_count_ip = all_count_ip + $yesterdayData[day_count_ip]
			";
			$this->_query( $sql );



			//Update Month Table
			$yesterdayMonthTime = mktime (0,0,0,$yesterdayMonth, 1, $yesterdayYear );
			$res = $this->_query( " select count(*) as count from " . $this->tableList[month_data] . " where times = $yesterdayMonthTime" );
			$row = mysql_fetch_array( $res, MYSQL_ASSOC );

			if( $row[count] == 0 )
			{
				$sql = " insert into " . $this->tableList[month_data] . "
				( times, year, month, month_count, month_count_ip )
				values
				( $yesterdayMonthTime, $yesterdayYear, $yesterdayMonth, $yesterdayData[day_count], $yesterdayData[day_count_ip] )
				";
				$this->_query( $sql );
			}
			else
			{
				$sql = " update " . $this->tableList[month_data] . " set month_count = month_count + $yesterdayData[day_count], month_count_ip = month_count_ip + $yesterdayData[day_count_ip] where times = $yesterdayMonthTime ";
				$this->_query( $sql );
			}

			//Update Year Table
			$yesterdayYearTime = mktime ( 0, 0, 0, 1, 1, $yesterdayYear );
			$res = $this->_query( " select count(*) as count from " . $this->tableList[year_data] . " where times = $yesterdayYearTime" );
			$row = mysql_fetch_array( $res, MYSQL_ASSOC );

			if( $row[count] == 0 )
			{
				$sql = " insert into " . $this->tableList[year_data] . "
				( times, year, year_count, year_count_ip )
				values
				( $yesterdayYearTime, $yesterdayYear, $yesterdayData[day_count], $yesterdayData[day_count_ip] )
				";
				$this->_query( $sql );
			}
			else
			{
				$sql = " update " . $this->tableList[year_data] . " set year_count = year_count + $yesterdayData[day_count], year_count_ip = year_count_ip + $yesterdayData[day_count_ip] where times = $yesterdayYearTime ";

				$this->_query( $sql );
			}


			//删除昨日详细访问统计
			$this->_query( "delete from " . $this->tableList[ip] . " where time < {$this->dayStartTime}" );

			foreach( $this->arrTypes as $key=>$val )
			{
				$sql = "delete from " . $this->tableList[$key] . " where types = 2 ";
				$this->_query( $sql );
				$sql = "update " . $this->tableList[$key] . " set types = 2 where types = 1 ";
				$this->_query( $sql );
			}


			//删除昨日产生的临时文件
			@rmdir( $this->userDataDir . '/' . $yesterdayStartTime );
		}

		function iniToday()
		{
			$sql = "INSERT INTO " . $this->tableList[day_data] . " (
													`times`, `year`, `month`, `day`, `week`
													) VALUES (
													'{$this->dayStartTime}', '{$this->year}', '{$this->month}', '{$this->day}', '{$this->week}'
													);";
			$this->_query( $sql );
		}

		function getFLTime( $val )
		{
			$val = explode( '-', $val );
			return mktime ( $val[3], $val[4], $val[5], $val[1], $val[2], $val[0] );
		}

		function getViewerInfo()
		{
			$this->viewerInfo[TIME] = &$this->time;
			$this->viewerInfo[page] = $_GET[pageurl];
			$this->viewerInfo[REFERER] = $_GET[referer];
			$this->viewerInfo[language] = strtolower( $_GET[language] );
			$this->viewerInfo[color] = $_GET[color];
			$this->viewerInfo[screen] = $_GET[screensize];
			$this->viewerInfo[HTTP_USER_AGENT] = $_SERVER["HTTP_USER_AGENT"];
			$this->viewerInfo[REMOTE_ADDR] = $_SERVER["REMOTE_ADDR"];
			$this->viewerInfo[timezone] = $_GET["timezone"];
			$this->viewerInfo[firsttime] = $this->getFLTime( $_GET["firsttime"] );
			$this->viewerInfo[lasttime] = $this->getFLTime( $_GET["lasttime"] );
			$this->viewerInfo['return'] = intval( $_GET['return1'] );
			$this->viewerInfo['counturl'] = $_GET['counturl'];

			$this->viewerInfo[charset] = strtolower ($_GET["charset"] );
			$this->viewerInfo[type] = intval( $_GET["type"] );


			//来自站点
			preg_match( "|(http://[^/]+?)/.*|isU", $this->viewerInfo[REFERER], $tmp );
			$this->viewerInfo[referer] = trim( $tmp[1] );

			//查找关键字
			$this->getKeyWord();

			//查找来源地区
			$ipInfo = $this->getIpAdd( );
			//_d( $ipInfo );
			$this->viewerInfo[country] = $ipInfo[country];
			$this->viewerInfo[address] = $ipInfo[address];
			$this->viewerInfo[province] = $ipInfo[province];
			$this->viewerInfo[city] = $ipInfo[city];

			//查找是否有alexa工具条
			if( strpos( $this->viewerInfo[HTTP_USER_AGENT], 'Alexa') )
			{
				$this->viewerInfo[alexatool] = 1;
			}
			else
			{
				$this->viewerInfo[alexatool] = 0;
			}

			//获取浏览器信息
			$this->getBrowser();
			$this->getSystem();
		}

		function saveViewerInfo()
		{
			$sql = "INSERT INTO " . $this->tableList[ip] . " (
								`ip`, `time`, `pageurl`, `pagefrom`, `language`, `color`, `screensize`, `http_user_agent`, `pagefromsite`, `keyword`, `country`, `address`, `province`, `city`, `alexatool`, `timezone`, `firsttime`, `lasttime`, `browser`, `system`, `todayfirst`, `return`
								) VALUES (
								'{$this->viewerInfo[REMOTE_ADDR]}', '{$this->viewerInfo[TIME]}', '{$this->viewerInfo[page]}', '{$this->viewerInfo[REFERER]}', '{$this->viewerInfo[language]}', '{$this->viewerInfo[color]}', '{$this->viewerInfo[screen]}', '{$this->viewerInfo[HTTP_USER_AGENT]}', '{$this->viewerInfo[referer]}', '{$this->viewerInfo[keyword]}', '{$this->viewerInfo[country]}', '{$this->viewerInfo[address]}', '{$this->viewerInfo[province]}', '{$this->viewerInfo[city]}', '{$this->viewerInfo[alexatool]}', '{$this->viewerInfo[timezone]}', '{$this->viewerInfo[firsttime]}', '{$this->viewerInfo[lasttime]}', '{$this->viewerInfo[browser]}', '{$this->viewerInfo[system]}', '" . ( $this->newViewer == true ? 1 : 0 ) . "', '".$this->viewerInfo['return']."' );";

			$this->_query( $sql );
		}

		function _error( $msg )
		{
			exit( $msg );
		}



		function ip2num( $ip )
		{
			$ipData = explode( '.', $ip );
			if( count( $ipData ) != 4 )
			{
				return 0;
			}
			$ipNum = 0;
			foreach( $ipData as $key => $val )
			{
				$ipNum += intval( $val ) * pow ( 256, 3-$key );
			}
			return $ipNum;
		}

		//获取ip地址来源
		function getIpAdd( )
		{
			$ipNum = $this->ip2num( $this->viewerInfo[REMOTE_ADDR] );
			$res = $this->_query( " select * from " . $this->tableList[ip_data] . " where ipstart <= $ipNum and ipend >= $ipNum" );
			$ipInfo = mysql_fetch_array( $res, MYSQL_ASSOC );
			return $ipInfo;
		}

		//处理alexa工具条数据
		function addAlexa()
		{
			if( $this->viewerInfo[alexatool] != 1 || $this->newViewer == false )
			{
				return false;
			}

			//$Time = mktime (0, 0, 0, $this->month, $this->day, $this->year);

			$sql = " select  count(*) as count from " . $this->tableList[alexa] . " where times={$this->dayStartTime} ";
			$res = $this->_query( $sql );

			//检查是否有需要添加的记录
			$tmp = mysql_fetch_array( $res, MYSQL_ASSOC );
			if( $tmp[count] == 0 )
			{
					$sql = "INSERT INTO " . $this->tableList[alexa] . " ( `times`, `lastpage`, `counts` ) VALUES ( '{$this->dayStartTime}', '{$this->viewerInfo[REFERER]}', '0' );";
					$this->_query( $sql );
			}

			$sql = " update " . $this->tableList[alexa] . " set counts = counts + 1, lastpage='{$this->viewerInfo[REFERER]}', http_user_agent = '{$this->viewerInfo[HTTP_USER_AGENT]}' where times={$this->dayStartTime} ";
			$this->_query( $sql );
		}


		//保存各个属性信息
		function saveArr()
		{
			foreach( $this->arrTypes as $key=>$val )
			{
				if( ( $this->viewerInfo[$key] == '' && $val[allownull] == false ) || ( $this->newViewer == false && $val[newviewer] == true ) )
				{
					continue;
				}

				$this->_SaveType( $key );
			}
		}

		function _saveType( $type )
		{
			$types = &$this->arrTypes;

			if( ! isset( $types[$type] ) )
			{
				return false;
			}


			$sql = " select count(*) as count, types, counts, {$type}id from " . $this->tableList[$type] . " where `{$type}` = '" . $this->viewerInfo["$type"] . "' and types != 2 group by types,{$type}id,counts ";
			$res = $this->_query( $sql );

			unset( $delData );
			unset( $data );

			while( $tmp = mysql_fetch_array( $res, MYSQL_ASSOC ) )
			{
				if( isset( $data["$tmp[types]"] ) )
				{
					$tmp['isset'] = $data["$tmp[types]"];
					$delData[] = $tmp;
					continue;
				}
				$data["$tmp[types]"] = $tmp;
			}

			//检查是否有需要添加的记录
			for( $i = 0; $i < 2; $i++ )
			{
				if( ! isset( $data[$i] ) )
				{
					$sql = "INSERT INTO " . $this->tableList[$type] . " ( `{$type}`, `times`,"  . ( $types[$type][lastpage] ?  "`lastpage`," : '' ) . " `counts`, `types` ) VALUES ( '" . $this->viewerInfo["$type"] . "', '{$this->viewerInfo[TIME]}', " . ( $types[$type][lastpage] ?  "'{$this->viewerInfo[REFERER]}', " : '' ) . "'0', '$i' );";
					$this->_query( $sql );
				}
			}

			//检查是否有需要删除的记录
			if( count( $delData ) > 0 )
			{
				foreach( $delData as $val )
				{
					$sql = " delete from " . $this->tableList[$type] . " where {$type}id = " . $val["{$type}id"];
					$this->_query( $sql );
					$sql = " update " . $this->tableList[$type] . " set counts = counts + $val[counts] where {$type}id = " . $val['isset']["{$type}id"];
					$this->_query( $sql );
				}
			}

			$sql = " update " . $this->tableList[$type] . " set counts = counts + 1, "  . ( $types[$type][lastpage] ?  "lastpage='{$this->viewerInfo[REFERER]}', " : '' ) . "times = '{$this->viewerInfo[TIME]}' where `{$type}` = '" . $this->viewerInfo["$type"] . "'  and types != 2";

			$this->_query( $sql );

		}

		function _query( $sql, $d = false )
		{
			$res = mysql_query( $sql );

			if( $d || $_GET[debug] == 'true'  )
			{
				echo $sql . "<br>\n";
				echo mysql_error();
			}

			if( $res )
			{
				return $res;
			}
			else
			{
				$f = fopen( '../count/mysql_error.log', 'a+' );
				fwrite( $f, date("Y-m-d H:i:s") . mysql_error() . '--' . $sql . "\n" );
				fclose( $f );
				return false;
			}
		}


	}




?>